import { constantRouterMap } from '@/router'
import { getRouters } from '@/api/router'
import { parseRouters } from '@/common/utils/index'

const permission = {
    state: {
        routers: constantRouterMap,
        addRouters: [],
        allPathList: ['/', '/login', '/layout', '/preview', '/redirect', '/404', 'formMaking', 'formMakingPreview'],
        asyncRouters: {}
    },
    mutations: {
        SET_ROUTERS: (state, routers) => {
            state.addRouters = routers
            state.routers = constantRouterMap.concat(routers)
        },
        SET_ALLPATH: (state, path) => {
            state.allPathList = state.allPathList.concat(path)
        },
        ADD_ROUTES: (state, data) => {
            state.asyncRouters = Object.assign({}, state.asyncRouters, { [data.name]: data.component })
        }
    },
    actions: {
        GenerateRoutes({ commit }, payload) {
            return new Promise((resolve, reject) => {
                getRouters(payload.userid).then(response => {
                    if (!response.data) {
                        commit('SET_ROUTERS', parseRouters([]))
                    } else {
                        commit('SET_ROUTERS', parseRouters(response.data))
                    }
                    resolve(response)
                }).catch(err => {
                    console.log(err)
                    reject(err)
                })
            })
        },
        registRouter({ commit }, payload) {
            return new Promise((resolve, reject) => {
                if (payload.routers.length) {
                    commit('SET_ROUTERS', payload.routers)
                    resolve()
                } else {
                    reject()
                }
            })
        }
    }
}

export default permission
